<template>
  <div class="document-system">
    <h1>律师文件管理</h1>


    <!-- 2. 新增这部分：标签页导航按钮 -->
    <div class="tab-nav">
      <button
        @click="activeTab = 'download'"
        :class="activeTab === 'download' ? 'tab-btn active' : 'tab-btn'"
      >
        模板下载
      </button>
      <button
        @click="activeTab = 'upload'"
        :class="activeTab === 'upload' ? 'tab-btn active' : 'tab-btn'"
      >
        文件上传
      </button>
    </div>


    <!-- 功能区域 -->
    <div class="tabs-container">
      <!-- 3. 给模板下载加 v-if="activeTab === 'download'" -->
      <div class="tab-content" v-if="activeTab === 'download'">
        <h2>模板下载</h2>
        <div class="template-list">
          <!-- 只保留一个通用模板 -->
          <div class="template-item">
            <div class="template-info">
              <h3>入所流程</h3> <!-- 改为“入所流程” -->
              <div class="required-docs">
                <span>需上传的证件: {{ requiredDocuments.join('、') }}</span>
              </div>
            </div>
            <!-- 绑定本地下载方法 -->
            <button
              class="download-btn"
              @click="downloadLocalTemplate"
            >
              <i class="icon-download"></i> 下载模板
            </button>
          </div>
        </div>
      </div>

      <!-- 文件上传 -->
      <!-- 3. 给文件上传加 v-if="activeTab === 'upload'" -->
      <div class="tab-content" v-if="activeTab === 'upload'">
        <h2>文件上传</h2>

        <div class="upload-form">
          <!-- 新增上传者名称输入框 -->
          <div class="form-group">
            <label>上传者名称:</label>
            <input
              type="text"
              v-model="uploadName"
              placeholder="请输入您的名字"
              class="upload-name-input"
            >
          </div>

          <div class="form-group">
            <label>上传填写好的PDF表单:</label>
            <div class="file-upload">
              <input
                type="file"
                accept=".pdf"
                @change="handleFormFileChange"
              >
              <span v-if="formFileName">{{ formFileName }}</span>
            </div>
          </div>

          <!-- 证件上传区域 - 直接显示所有需要的证件 -->
          <div>
            <h3>请上传以下证件:</h3>
            <div
              class="document-upload"
              v-for="doc in requiredDocuments"
              :key="doc"
            >
              <label>{{ doc }}:</label>
              <div class="file-upload">
                <input
                  type="file"
                  accept=".jpg,.jpeg,.png,.pdf"
                  @change="handleDocFileChange($event, doc)"
                >
                <span v-if="uploadedDocs[doc]">{{ uploadedDocs[doc].name }}</span>
              </div>
            </div>
          </div>

          <button
            class="submit-btn"
            @click="submitUpload"
            :disabled="!canSubmit"
          >
            提交审核
          </button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import instance from '@/service/index.js'; // 替换原axios导入
// 1. 新增这行：标签页选中状态（默认显示“模板下载”）
const activeTab = ref('download');



// 2. 添加本地模板下载方法
const downloadLocalTemplate = () => {
  // 本地PDF路径（假设文件放在public/templates/入所流程.pdf）
  const templatePath = '/template/入所流程.docx';// 创建下载链接
  const link = document.createElement('a');
  link.href = templatePath;
  link.download = '入所流程.docx'; // 下载时显示的文件名
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  ElMessage.success('入所流程模板下载成功'); // 更新提示文字
};

// 固定需要上传的证件列表（无需选择模板）
const requiredDocuments = ref(['身份证', '毕业证', '律师执业证']);

// 上传相关数据
const formFile = ref(null);
const formFileName = ref('');
const uploadedDocs = reactive({});
const pendingSubmissions = ref([]);
const uploadName=ref('');

// 检查是否可以提交
const canSubmit = computed(() => {
  // 检查表单文件是否已上传
  if (!formFile.value) {
    return false;
  }

  // 检查所有必填证件是否已上传
  return requiredDocuments.value.every(doc => {
    return uploadedDocs[doc] !== undefined;
  });
});

// 处理表单文件选择
const handleFormFileChange = (e) => {
  const file = e.target.files[0];
  if (file) {
    formFile.value = file;
    formFileName.value = file.name;
  }
};

// 处理证件文件选择
const handleDocFileChange = (e, docName) => {
  const file = e.target.files[0];
  if (file) {
    uploadedDocs[docName] = file;
  }
};

// 下载模板
const downloadTemplate = (template) => {
  instance({
    url: `/api/templates/${template.id}/download`,
    method: 'GET',
    responseType: 'blob'
  }).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.download = `${template.name}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('模板下载成功');
  }).catch(error => {
    ElMessage.error('下载失败: ' + (error.message || '未知错误'));
  });
};

// 提交上传
const submitUpload = () => {
  const formData = new FormData();
  // formData.append('lawyerId', currentUser.id);

  formData.append('uploadName', uploadName.value.trim());
  formData.append('formFile', formFile.value);

  // 添加证件文件
  Object.keys(uploadedDocs).forEach(docName => {
    formData.append(`documents[${docName}]`, uploadedDocs[docName]);
  });

  instance.post('/api/submissions', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then(response => {
    ElMessage.success('提交成功，等待审核');
    // 重置表单
    formFile.value = null;
    formFileName.value = '';
    uploadName.value = '';
    Object.keys(uploadedDocs).forEach(key => {
      delete uploadedDocs[key];
    });
  }).catch(error => {
    ElMessage.error('提交失败: ' + (error.message || '未知错误'));
  });
};


// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

// 页面加载时获取数据
onMounted(() => {

});
</script>

<style>
.document-system {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1, h2, h3 {
  color: #333;
}

.tabs-container {
  margin-top: 30px;
}

.tab-content {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}


.template-list {
  margin-top: 20px;
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  margin-bottom: 15px;
  border: 1px solid #eee;
}

.template-info {
  flex: 1;
}

.required-docs {
  margin-top: 8px;
  color: #666;
  font-size: 0.9em;
}

.download-btn, .submit-btn, .approve-btn, .reject-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}

.download-btn {
  background-color: #4285f4;
  color: white;
}

.upload-form {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group select {
  width: 300px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.file-upload {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-upload input {

  padding: 5px;
}

.file-upload span {
  color: #666;
  font-size: 0.9em;
}

.document-upload {
  margin-bottom: 15px;
}

.submit-btn {
  background-color: #0f9d58;
  color: white;
  padding: 10px 20px;
  font-size: 1em;
}

.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.submissions-list {
  margin-top: 20px;
}

.submission-item {
  background-color: white;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.submission-info {
  flex: 1;
}


.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 6px;
  width: 500px;
}

.modal-content textarea {
  width: 100%;
  height: 100px;
  margin: 15px 0;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.modal-actions button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.modal-actions button:last-child {
  background-color: #db4437;
  color: white;
  border-color: #db4437;
}


/* 标签页导航样式 */
.tab-nav {
  display: flex;
  gap: 2px;
  margin-top: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 2px;
}
/* 未选中的标签按钮 */
.tab-btn {
  padding: 8px 16px;
  border: none;
  background: #f5f5f5;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
  font-weight: 500;
  color: #666;
}
/* 选中的标签按钮（高亮） */
.tab-btn.active {
  background: #4285f4;
  color: white;
}

</style>

